package com.tianhui.consignortwofei.mvp.ui.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.fgs.common.CommonFragment;
import com.fgs.common.CommonPresenter;
import com.fgs.common.CommonResponse;
import com.fgs.common.CommonView;
import com.fgs.common.entity.CommonDataListInfo;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.base.BaseDataListActivity;
import com.tianhui.consignortwofei.constant.KeyValue;
import com.tianhui.consignortwofei.mvp.model.MessageModel;
import com.tianhui.consignortwofei.mvp.model.enty.message.MessageInfo;
import com.tianhui.consignortwofei.mvp.ui.adapter.MessageListAdapter;

import org.yczbj.ycrefreshviewlib.adapter.RecyclerArrayAdapter;
import org.yczbj.ycrefreshviewlib.inter.OnItemChildClickListener;
import org.yczbj.ycrefreshviewlib.swipe.OnSwipeMenuListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * @author fgs
 * @date 2020/9/10
 * @description
 **/
public class MessageListActivity extends BaseDataListActivity {

    @BindView(R.id.activity_message_list_editTextView)
    TextView mEditTextView;
    @BindView(R.id.activity_message_list_editLinearLayout)
    LinearLayout mEditLinearLayout;

    @BindView(R.id.activity_message_list_deleteTextView)
    TextView mDeleteTextView;
    @BindView(R.id.activity_message_list_saveTextView)
    TextView mSaveTextView;
    @BindView(R.id.activity_message_list_cancelTextView)
    TextView mCancelTextView;
    private MessageListAdapter mMessageListAdapter;
    private List<MessageInfo> mSelectedMessageList = new ArrayList<>();
    private List<MessageInfo> mRealMessageList = new ArrayList<>();
    private int mMessageType;
    private MessageModel mMessageModel;

    @Override
    public int getLayoutId() {
        return R.layout.activity_message_list;
    }

    @Override
    public CommonPresenter createPresenter() {
        return null;
    }

    @Override
    public CommonView createView() {
        return null;
    }

    @Override
    public CommonFragment createFragment() {
        return null;
    }

    @Override
    public RecyclerArrayAdapter createAdapter() {
        mMessageListAdapter = new MessageListAdapter(this);
        return mMessageListAdapter;
    }

    @Override
    protected void initListener() {

        mEditTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mMessageListAdapter.getCount() != 0) {
                    mEditLinearLayout.setVisibility(View.VISIBLE);
                    mEditTextView.setVisibility(View.GONE);
                    showEditStatus(true);
                } else {
                    showToast("没有可操作的消息");
                }

            }
        });
        mDeleteTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取选中的消息
                mSelectedMessageList = mMessageListAdapter.getSelectedMessage();
                if (mSelectedMessageList != null && mSelectedMessageList.size() > 0) {
                    List<MessageInfo> list = new ArrayList<>();
                    int size = mMessageListAdapter.getCount();
                    MessageInfo messageInfo;
                    for (int i = 0; i < size; i++) {
                        messageInfo = mMessageListAdapter.getAllData().get(i);
                        if (!messageInfo.isChecked) {
                            list.add(messageInfo);
                        }
                    }
                    mMessageListAdapter.clear();
                    mMessageListAdapter.addAll(list);
                    checkIsShowEmpty();
                } else {
                    showToast("请先选中要删除的消息");
                }

            }
        });
        mSaveTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                multipleDeleteMessage(getRemoveMessageIds());
            }
        });
        mCancelTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditLinearLayout.setVisibility(View.GONE);
                mEditTextView.setVisibility(View.VISIBLE);
                showEditStatus(false);
                mMessageListAdapter.clear();
                mMessageListAdapter.addAll(mRealMessageList);
            }
        });

        mMessageListAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(View view, int position) {
                switch (view.getId()) {
                    case R.id.item_message_list_itemLinearLayout:
                        MessageInfo messageInfo = mMessageListAdapter.getAllData().get(position);
                        if (messageInfo != null) {
                            if (messageInfo.remindFlag == 0) {
                                requestReadMessage(position, messageInfo);
                            } else {
                                openMessageDetailActivity(messageInfo);
                            }
                        }
                        break;
                }
            }
        });

        mMessageListAdapter.setOnSwipeMenuListener(new OnSwipeMenuListener() {
            @Override
            public void toDelete(int position) {
                int size = mMessageListAdapter.getCount();
                if (position < size) {
                    MessageInfo messageInfo = mMessageListAdapter.getAllData().get(position);
                    singleDeleteMessage(messageInfo.id, position);
                }
            }

            @Override
            public void toTop(int position) {

            }
        });
    }

    private void singleDeleteMessage(String id, int position) {
        requestRemoveMessage(1, id, position);
    }

    private void multipleDeleteMessage(String ids) {
        requestRemoveMessage(0, ids, 0);
    }

    // 0 批量删除 1 单条删除
    private void requestRemoveMessage(int removeType, String ids, int position) {
        Map<String, String> map = new HashMap<>();
        map.put("ids", ids);
        mMessageModel.removeMessageModel(this, map, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    if (removeType == 0) {
                        mEditLinearLayout.setVisibility(View.GONE);
                        mEditTextView.setVisibility(View.VISIBLE);
                        showEditStatus(false);
                        mRealMessageList = mMessageListAdapter.getAllData();
                    } else {
                        mMessageListAdapter.remove(position);
                        checkIsShowEmpty();
                    }

                } else {
                    showToast(commonResponse.getMsg());
                }

            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });
    }

    private String getRemoveMessageIds() {
        StringBuilder stringBuilder = new StringBuilder();
        for (MessageInfo info : mSelectedMessageList) {
            stringBuilder.append(info.id);
            stringBuilder.append(",");
        }
        return stringBuilder.toString();
    }

    private void checkIsShowEmpty() {
        if (mMessageListAdapter.getCount() == 0) {
            showEmptyView();
        }
    }

    private void showEditStatus(boolean isEdit) {
        mMessageListAdapter.setEdit(isEdit);
        mMessageListAdapter.notifyDataSetChanged();
    }

    private void openMessageDetailActivity(MessageInfo messageInfo) {
        Bundle bundle = new Bundle();
        bundle.putParcelable(KeyValue.KEY_MESSAGE_INFO, messageInfo);
        openActivity(MessageDetailActivity.class, bundle);
    }

    private void requestReadMessage(int position, MessageInfo messageInfo) {
        Map<String, String> map = new HashMap<>();
        map.put("id", messageInfo.id);
        mMessageModel.readMessageModel(this, map, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    if (messageInfo.remindFlag == 0) {
                        messageInfo.remindFlag = 1;
                        mMessageListAdapter.notifyItemChanged(position);
                    }
                    openMessageDetailActivity(messageInfo);
                } else {
                    showToast(commonResponse.getMsg());
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });

    }

    @Override
    public void requestDataList(int page, boolean isDialog) {
        Map<String, String> map = new HashMap<>();
        map.put("page", page + "");
        map.put("limit", "10");
        map.put("type", mMessageType + "");

        mMessageModel.messageListModel(this, map, isDialog, this.bindLifecycle(), new ObserverResponseListener<CommonResponse<CommonDataListInfo>>() {
            @Override
            public void onNext(CommonResponse<CommonDataListInfo> commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    CommonDataListInfo dataListInfo = commonResponse.getData();
                    setPageInfo(dataListInfo.current, dataListInfo.pages);
                    List<MessageInfo> list = dataListInfo.records;
                    if (list != null && list.size() > 0) {
                        showDataList(list);
                    } else {
                        showEmptyView();
                    }
                } else {
                    showEmptyView();
                }

            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
                showEmptyView();
                stopRefresh();
            }
        });
    }

    @Override
    public void showDataList(List data) {
        super.showDataList(data);
        mRealMessageList = mAdapter.getAllData();
    }

    @Override
    public String getToolbarTitle() {
        return "消息列表";
    }

    @Override
    public void initData() {

        mMessageModel = new MessageModel();

        Bundle bundle = getIntent().getExtras();
        if (bundle != null && !bundle.isEmpty()) {
            mMessageType = bundle.getInt(KeyValue.KEY_TYPE);
        }

    }
}
